package com.example.sfm.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.util.Arrays;
import java.util.List;

public class TemplateStyleHandler extends AbstractColumnWidthStyleStrategy
        implements WriteHandler {

    private static final List<String> NOTE_LINES = Arrays.asList(
            "填写说明：",
            "1. 学号：必须为系统中存在的学生ID",
            "2. 课程编号：必须为系统中存在的课程ID",
            "3. 成绩：0.00-100.00之间的数值（可含两位小数）",
            "4. 等级：0(不及格)/1(及格)/2(良好)/3(优秀)",
            "5. 考试日期：格式必须为yyyy-MM-dd（例如：2024-03-20）"
    );

    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder,
                                 WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        addTemplateNotes(sheet);
    }

    private void addTemplateNotes(Sheet sheet) {
        Drawing<?> drawing = sheet.createDrawingPatriarch();

        // 添加注释框
        Comment comment = drawing.createCellComment(
                new XSSFClientAnchor(0, 0, 0, 0, 0, 5, 4, 8));

        // 设置注释内容
        RichTextString str = new XSSFRichTextString(String.join("\n", NOTE_LINES));
        comment.setString(str);
        comment.setAuthor("系统提示");

        // 将注释关联到A1单元格
        Cell cell = sheet.getRow(0).getCell(0);
        cell.setCellComment(comment);
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder,
                                  List<WriteCellData<?>> cellDataList,
                                  Cell cell, Head head, Integer relativeRowIndex,
                                  Boolean isHead) {
        if (isHead) {
            cell.getSheet().setColumnWidth(cell.getColumnIndex(), 20 * 256);
        }
    }
}